<template>
  <div class="app-container goods">
    <!-- 筛选部分 -->
    <div class="app-container-hd">
      <div class="toolbar-search">
        <div class="table-top-button">
          <div>
            <el-button icon="el-icon-printer" type="primary" size="mini" @click="handlePrint">单据打印</el-button>
            <el-button icon="el-icon-download" type="primary" size="mini" @click="handleExport">导出数据</el-button>
            <el-button icon="el-icon-printer" type="primary" size="mini" @click="handlePrintLabel(false)">打印标签</el-button>
            <el-button icon="el-icon-edit" type="primary" size="mini" :disabled="selected.length <= 0" @click="handleUpdateAll">批量修改</el-button>
            <el-button icon="el-icon-delete" type="danger" size="mini" :disabled="selected.length <= 0" @click="handleDestroyAll">批量删除</el-button>
            <el-button icon="el-icon-plus" type="primary" size="mini" @click="filterModal = true">自定义显示</el-button>
          </div>
          <div>
            <el-button v-if="showSearch" type="primary" @click="showSearch = false">收起<i class="el-icon-arrow-up el-icon--right" /></el-button>
            <el-button v-else type="primary" @click="showSearch = true">展开<i class="el-icon-arrow-down el-icon--right" /></el-button>
          </div>
        </div>
        <el-form v-if="showSearch" ref="searchParams" :model="searchParams" :inline="true" size="mini" @keyup.enter.native="handleSearch">
          <el-form-item v-if="searchItem.indexOf(1) < 0" label="上架时间:" prop="released_at">
            <el-date-picker
              v-model="searchParams.released_at"
              clearable
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
            />
          </el-form-item>
          <el-form-item v-if="searchItem.indexOf(2) < 0" label="标号:" prop="goods_code">
            <el-input v-model="searchParams.goods_code" placeholder="请输入标号" clearable style="width: 180px" />
          </el-form-item>
          <el-form-item v-if="searchItem.indexOf(3) < 0" label="聚星字号:" prop="goods_name">
            <el-input v-model="searchParams.goods_name" placeholder="请输入聚星字号搜索" clearable style="width: 180px" />
          </el-form-item>
          <el-form-item v-if="searchItem.indexOf(4) < 0" label="货主:" prop="supplier_id">
            <el-select v-model="searchParams.supplier_id" placeholder="请选择货主" clearable>
              <el-option v-for="item in supplierList" :key="item.supplier_id" :label="item.name" :value="item.supplier_id" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="searchItem.indexOf(5) < 0" prop="is_show" label="是否展示">
            <el-select v-model="searchParams.is_show" size="mini">
              <el-option label="否" :value="0" />
              <el-option label="是" :value="1" />
            </el-select>
          </el-form-item>

          <el-form-item v-if="searchItem.indexOf(6) < 0" prop="is_bid" label="是否参与投标">
            <el-select v-model="searchParams.is_bid" size="mini">
              <el-option label="否" :value="0" />
              <el-option label="是" :value="1" />
            </el-select>
          </el-form-item>

          <el-form-item v-if="searchItem.indexOf(7) < 0" prop="is_onshelf" label="是否上架">
            <el-select v-model="searchParams.is_onshelf" size="mini">
              <el-option label="否" :value="0" />
              <el-option label="是" :value="1" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="searchItem.indexOf(8) < 0" label="备注搜索:" prop="remarks">
            <el-input v-model="searchParams.remarks" placeholder="请输入备注中的关键字" clearable style="width: 180px" />
          </el-form-item>
          <div class="form-button">
            <el-form-item>
              <el-button icon="el-icon-search" type="primary" @click="handleSearch">筛选</el-button>
            </el-form-item>
            <el-form-item>
              <el-button icon="el-icon-refresh" @click="handleSearch('searchParams', 'reset')">重置</el-button>
            </el-form-item>
          </div>
        </el-form>
      </div>

      <!-- 表格部分 -->
      <div v-loading="$store.state.app.loading" class="table-main fixed">
        <el-table
          row-key="goods_id"
          highlight-current-row
          :data="listData"
          :border="true"
          height="600"
          :empty-text="$store.state.app.loading ? '正在加载数据' : null"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="48" fixed align="center" />
          <el-table-column v-if="fieldItem.indexOf(1) < 0" prop="goods_code" label="标号" width="80" />
          <el-table-column v-if="fieldItem.indexOf(2) < 0" prop="goods_name" label="聚星字号" min-width="100" />
          <el-table-column v-if="fieldItem.indexOf(3) < 0" prop="image" label="图片" width="88" align="center">
            <template slot-scope="item">
              <el-image
                style="width: 70px; height: 70px;margin-top: 8px;margin-left: -2px;cursor: pointer"
                :src="item.row.cover | media"
                fit="cover"
                @click="previewImages(item.row)"
              ><div slot="error" class="image-slot"><i class="el-icon-picture-outline" /></div>
              </el-image>
            </template>
          </el-table-column>
          <el-table-column v-if="fieldItem.indexOf(4) < 0" prop="stock" label="片数" width="80" />
          <el-table-column v-if="fieldItem.indexOf(5) < 0" prop="weight" label="重量" width="100" />
          <el-table-column v-if="fieldItem.indexOf(6) < 0" prop="seat" label="位置" width="100" />
          <el-table-column v-if="fieldItem.indexOf(7) < 0" prop="label_price" label="底价" width="100" />
          <el-table-column v-if="fieldItem.indexOf(8) < 0" prop="supplier.name" label="货主" width="120" />
          <el-table-column v-if="fieldItem.indexOf(9) < 0" prop="remarks" label="备注信息" min-width="120" />
          <el-table-column v-if="fieldItem.indexOf(10) < 0" prop="is_bid" label="投标状态" width="120">
            <template slot-scope="item">
              <el-tag v-if="item.row.is_bid === 1" type="success" size="small" @click="handleUpdate(item.row, 'is_bid')">参与投标</el-tag>
              <el-tag v-else type="info" size="small" @click="handleUpdate(item.row, 'is_bid')">不参与投标</el-tag>
            </template>
          </el-table-column>
          <el-table-column v-if="fieldItem.indexOf(11) < 0" prop="is_onshelf" label="上下架状态" width="120">
            <template slot-scope="item">
              <el-tag v-if="item.row.is_onshelf === 1" type="success" size="small" @click="handleUpdate(item.row, 'is_onshelf')">上架</el-tag>
              <el-tag v-else type="info" size="small" @click="handleUpdate(item.row, 'is_onshelf')">下架</el-tag>
            </template>
          </el-table-column>
          <el-table-column v-if="fieldItem.indexOf(12) < 0" prop="is_show" label="前端展示" width="120">
            <template slot-scope="item">
              <el-tag v-if="item.row.is_show === 1" type="success" size="small" @click="handleUpdate(item.row, 'is_show')">是</el-tag>
              <el-tag v-else type="info" size="small" @click="handleUpdate(item.row, 'is_show')">否</el-tag>
            </template>
          </el-table-column>
          <el-table-column v-if="fieldItem.indexOf(13) < 0" prop="action" label="操作" width="100">
            <template slot-scope="item">
              <div class="button-group">
                <el-button type="text" size="mini" @click="handlePrintLabel(item.row)">打印标签</el-button>
                <el-button style="margin-left: 0" type="text" size="mini" @click="handleEdit(item.row)">编辑信息</el-button>
                <!-- <el-button style="margin-left: 0;color: #F56C6C" type="text" size="mini" @click="handleEdit(item.row)">删除商品</el-button> -->
                <el-button style="margin-left: 0;" type="text" size="mini" @click="handleRowDelete(item.row)">删除商品</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <div class="app-container-ft">
      <paginate :total="searchParams.total" :per-page="searchParams.per_page" :page="searchParams.page" @paginate-change="handleSearch" />
    </div>

    <!-- 数据编辑弹窗 -->
    <box-save
      v-if="showModal"
      :item-data="itemData"
      :mode="editMode"
      :option="{
        supplierList: supplierList,
        selected: selected
      }"
      @on-cancel-modal="acceptCancelModal"
    />
    <!-- 打印弹窗 -->
    <Print
      v-if="printModal"
      :print-data="printData"
      :tpl-id="tplId"
      :tpl-list="tplList"
      :cache-mark="cacheMark"
      @on-cancel-modal="acceptCancelModal"
    />

    <!-- Excel数据导出 -->
    <Export
      v-if="showExport"
      :field-list="exportFields"
      :data-list="dataList"
      @on-cancel-modal="acceptCancelModal"
    />

    <el-image-viewer
      v-if="showViewer"
      :on-close="closeViewer"
      :url-list="viewerList"
      style="z-index: 3000;"
    />

    <filter-item
      v-if="filterModal"
      :field-item="fieldItem"
      :search-item="searchItem"
      @on-cancel-modal="handleCancelModal"
    />
  </div>
</template>

<script>
import boxSave from './components/save'
import Export from './components/export'
import Paginate from '@/components/Paginate/index'
import Print from '@/components/Print'
import { initial, paginate, info, destroy, destroyAll, updateGoods } from '@/api/goods'
import { getPrintTplList } from '@/api/print-tpl'
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
import { mediaFilter } from '@/utils/filters'
import filterItem from './components/filterItem'

export default {
  components: { Paginate, boxSave, Print, Export, ElImageViewer, filterItem },
  data: function() {
    return {
      listData: [],
      supplierList: null,
      selected: [],
      multipleSelection: [],

      printModal: false,
      tplId: null,
      tplList: [],
      printData: null,
      cacheMark: null,

      showExport: false,
      exportFields: null,
      dataList: [],

      showViewer: false,
      viewerList: [],

      filterModal: false,
      searchItem: [],
      fieldItem: [],

      itemData: null,
      editMode: 'single',
      showModal: false,
      showSearch: true,
      searchParams: {
        goods_code: null,
        released_at: null,
        supplier_id: null,
        goods_name: null,
        description: null,
        remarks: null,
        status: null,
        is_onshelf: null,
        is_bid: null,
        is_show: null,
        total: null,
        page: null,
        per_page: parseInt(process.env.VUE_APP_PER_PAGE)
      }
    }
  },
  // computed: {
  //   ...mapGetters([
  //     'goodsId'
  //   ])
  // },
  mounted: function() {
    // 初始化方法
    this.initialize()

    const searchItem = localStorage.getItem('goods-list-search')
    const fieldItem = localStorage.getItem('goods-list-field')
    if (searchItem) {
      this.searchItem = JSON.parse(searchItem)
    }
    if (fieldItem) {
      this.fieldItem = JSON.parse(fieldItem)
    }
  },
  methods: {
    // 初始化数据列表
    initialize: function() {
      // 获取数据列表
      this.$store.commit('app/SET_LOADING', true)
      if (this.supplierList === null) {
        initial(function(res) {
          if (res !== false) {
            this.listData = res[0].data
            this.searchParams.total = parseInt(res[0].total)
            this.searchParams.page = parseInt(res[0].current_page)
            this.searchParams.per_page = parseInt(res[0].per_page)
            this.supplierList = res[1]
            console.log(res)
          }
          this.$nextTick(function() {
            this.$store.commit('app/SET_LOADING', false)
          })
        }.bind(this), this.searchParams)
      } else {
        paginate(this.searchParams).then(res => {
          this.listData = res.data
          this.searchParams.total = parseInt(res.total)
          this.searchParams.page = parseInt(res.current_page)
          this.searchParams.per_page = parseInt(res.per_page)
          this.$nextTick(function() {
            this.$store.commit('app/SET_LOADING', false)
          })
        })
      }
    },
    // 根据条件筛选数据
    handleSearch: function(value, field) {
      // 重置表单数据
      if (field === 'reset') {
        this.searchParams.page = 1
        this.$refs[value].resetFields()
        // 页码参数变更
      } else if (field) {
        this.searchParams.page = 1
        this.searchParams[field] = value
      }
      this.initialize()
    },
    // 关闭数据编辑窗口
    acceptCancelModal: function(modal, refresh = false) {
      if (refresh === true) {
        this.initialize()
      }
      this[modal] = false
    },
    handleEdit(row) {
      this.$store.commit('app/SET_LOADING', true)
      info({ goods_id: row['goods_id'] }).then(res => {
        this.editMode = 'single'
        this.itemData = res.data
        this.showModal = true
        this.$store.commit('app/SET_LOADING', false)
      })
    },
    handleUpdateAll() {
      this.editMode = 'batch'
      this.itemData = null
      this.showModal = true
    },
    // 删除列表指定数据
    handleRowDelete: function(row) {
      this.$confirm('该操作将彻底删除该数据切无法恢复，确定要继续吗?', '提示', {
        distinguishCancelAndClose: false,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '请稍等...'
            destroy(row.goods_id).then(function() {
              done()
              this.initialize()
              instance.confirmButtonLoading = false
              instance.confirmButtonText = '确定'
            }.bind(this)).catch(function() {
              instance.confirmButtonLoading = false
              instance.confirmButtonText = '确定'
            })
          } else {
            done()
            instance.confirmButtonLoading = false
            instance.confirmButtonText = '确定'
          }
        }
      })
    },
    handleDestroyAll() {
      this.$confirm('该操作将删除选中的数据，确定要继续吗?', '提示', {
        distinguishCancelAndClose: false,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '请稍等...'
            destroyAll({ goods_ids: this.selected }).then(function() {
              done()
              this.initialize()
              instance.confirmButtonLoading = false
              instance.confirmButtonText = '确定'
            }.bind(this)).catch(function() {
              instance.confirmButtonLoading = false
              instance.confirmButtonText = '确定'
            })
          } else {
            done()
            instance.confirmButtonLoading = false
            instance.confirmButtonText = '确定'
          }
        }
      })
    },
    handleSelectionChange: function(data) {
      const selected = []
      for (let i = 0; i < data.length; i++) {
        selected.push(data[i]['goods_id'])
      }
      this.selected = selected
    },
    // 打印标签
    handlePrintLabel(item) {
      if (!item && this.selected.length <= 0) {
        this.$message.warning('请选择要打印的数据'); return false
      }
      // 缓存标识
      this.cacheMark = 'print-goods-label'
      this.$store.commit('app/SET_LOADING', true)
      this.tplId = parseInt(localStorage.getItem(this.cacheMark))
      Promise.all([
        paginate({ ...this.searchParams, is_export: 1, goods_ids: item ? [item.goods_id] : this.selected }),
        getPrintTplList({ mode: 'goods_label' })
      ]).then(res => {
        if (res !== false) {
          this.printData = this.handlePrintData(res[0].data)
          this.tplList = res[1].data
        }
        this.printModal = true
        this.$nextTick(function() {
          this.$store.commit('app/SET_LOADING', false)
        })
      })
    },
    handlePrintData(data) {
      const lists = data.map((e, index) => {
        return {
          ...e,
          index: index + 1,
          supplier: e.supplier && e.supplier.name
        }
      })
      console.log(lists)
      return {
        lists: lists
      }
    },
    // 单据打印
    handlePrint() {
      if (this.selected.length <= 0 && (!this.searchParams.released_at || this.searchParams.released_at.length !== 2)) {
        this.$message.warning('请选择要打印的数据，或选择时间范围'); return false
      } else {
        this.cacheMark = 'print-goods-list'
        this.$store.commit('app/SET_LOADING', true)
        this.tplId = parseInt(localStorage.getItem(this.cacheMark))
        const params = { ...this.searchParams, is_export: 1 }
        if (this.selected.length > 0) {
          params.goods_ids = this.selected
        }
        Promise.all([
          paginate(params),
          getPrintTplList({ mode: 'goods_list' })
        ]).then(res => {
          if (res !== false) {
            console.log(res)
            this.printData = this.handlePrintData(res[0].data)
            this.tplList = res[1].data
          }
          this.printModal = true
          this.$nextTick(function() {
            this.$store.commit('app/SET_LOADING', false)
          })
        })
      }
    },
    handleExport: function() {
      if (this.selected.length <= 0 && (!this.searchParams.released_at || this.searchParams.released_at.length !== 2)) {
        this.$message.warning('请选择要导出的数据，或选择时间范围')
      } else {
        this.exportFields = JSON.parse(localStorage.getItem('export-goods-fields'))
        this.$store.commit('app/SET_LOADING', true)
        const params = { ...this.searchParams, is_export: 1 }
        if (this.selected.length > 0) {
          params.goods_ids = this.selected
        }
        paginate(params).then(res => {
          this.dataList = this.handlePrintData(res.data).lists
          this.showExport = true
          this.$nextTick(function() {
            this.$store.commit('app/SET_LOADING', false)
          })
        })
      }
    },
    previewImages: function(item) {
      this.$store.commit('app/SET_LOADING', true)
      info({ goods_id: item.goods_id }).then(res => {
        this.viewerList = res.data.images.map(e => mediaFilter(e.path))
        // console.log(this.itemData)
        this.showViewer = true
        this.$nextTick(function() {
          this.$store.commit('app/SET_LOADING', false)
        })
      })
    },
    closeViewer() {
      console.log('closeViewer')
      this.showViewer = false
    },
    handleCancelModal: function(method, refresh = false) {
      if (refresh === true) {
        if (method === 'filterModal') {
          this.searchItem = JSON.parse(localStorage.getItem('goods-list-search'))
          this.fieldItem = JSON.parse(localStorage.getItem('goods-list-field'))
        } else {
          this.initialize()
        }
      }
      this[method] = false
    },
    handleUpdate(item, tag) {
      const params = {
        goods_id: item.goods_id
      }
      params[tag] = item[tag] ? 0 : 1
      this.$store.commit('app/SET_LOADING', true)
      updateGoods(params).then(() => {
        item[tag] = params[tag]
        this.$store.commit('app/SET_LOADING', false)
      })
    }
  }
}
</script>
<style lang="scss">
.goods .el-table {
  th {
    height: 48px;
    line-height: 48px;
  }
  td {
    height: 47.5px;
    color: #909399;
    line-height: 35px;
  }
  .el-table__expanded-cell .el-table {
    margin-left: 20px;
  }
}
</style>

<style lang="scss" scoped>
.table-top-button {
  display: flex;
  padding-bottom: 10px;
  justify-content: space-between;
}
</style>
